package com.fly.demo.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.fly.demo.entity.Article;
import com.fly.demo.service.init.DataInitor;

import lombok.extern.slf4j.Slf4j;

/**
 * DataService
 */
@Slf4j
@Service
public class DataService
{
    @Autowired
    List<DataInitor> dataInitors;
    
    /**
     * 获取url数据列表
     * 
     * @return
     * @throws IOException
     */
    @Cacheable(cacheNames = "data", key = "'articles'", sync = true)
    public List<Article> getArticles()
    {
        AtomicInteger count = new AtomicInteger();
        dataInitors.stream().forEach(d -> log.info("{}. {}", count.incrementAndGet(), d));
        
        // 串行流,有一个DataInitor执行init成功就返回
        List<Article> articles = new ArrayList<>();
        dataInitors.stream()
            .peek(d -> log.info("{}", d.getClass().getName())) // debug
            .anyMatch(d -> d.init(articles));
        log.info("############## articles.size: {} ", articles.size());
        return articles;
    }
}